<?php
/**
 *
 * @Allan
 * Date: 2020/12/4 12:31
 */

namespace app\common\traits;


use app\common\model\Country;
use app\common\model\sport\Club;
use app\common\model\sport\Team;
use app\common\utils\Functions;
use app\common\model\Sport\Score as SportScoreModel;
use app\common\model\Sport\Club as SportClubModel;
use app\common\model\Sport\Team as SportTeamModel;
use app\common\utils\Https;
use think\Exception;
use think\Log;

trait SportScore
{
    /**
     * 查询 资源
     * @param array $param
     * @return SportScoreModel
     */
    private static function query($param = []){
        $queryClub = SportClubModel::where([]);
        if(isset($param['type']) && !empty($param['type'])){
            $queryClub->where('type','=',intval($param['type']));
        }

        if(isset($param['version']) && !empty($param['version'])){
            $queryClub->where('version','=',trim($param['version']));
        }
        $clubIds = collection($queryClub->field('id')->select())->column('id');



        $query = SportScoreModel::where([]);

        if(isset($param['id']) && !empty($param['id'])){
            $query->where('id','=',intval($param['id']));
        }

        if(isset($param['type']) && !empty($param['type'])){
            $cList = SportClubModel::all(['type' => intval($param['type'])]);
            $query->where('country_id','in',array_column($cList,'country_id'));
        }

        if(isset($param['country_id']) && !empty($param['country_id'])){
            $query->where('country_id','in',explode(',',$param['country_id']));
        }

        if(isset($param['main_team_id']) && !empty($param['main_team_id'])){
            $query->where('main_team_id','in',explode(',',$param['main_team_id']));
        }

        if(isset($param['visiting_team_id']) && !empty($param['visiting_team_id'])){
            $query->where('visiting_team_id','in',explode(',',$param['visiting_team_id']));
        }

        if(isset($param['club_id']) && !empty($param['club_id'])){
            $query->where('club_id','in',explode(',',$param['club_id']));
        }else{
            $query->where('club_id','in',$clubIds);
        }

        if(isset($param['update_time_start']) && !empty($param['update_time_start'])){
            $query->where('update_time','>=',strtotime($param['update_time_start']));
        }
        if(isset($param['update_time_end']) && !empty($param['update_time_end'])){
            $query->where('update_time','<',strtotime($param['update_time_end']));
        }

        if(isset($param['match_time_start']) && !empty($param['match_time_start'])){
            $query->where('match_time','>=',strtotime($param['match_time_start']));
        }
        if(isset($param['match_time_end']) && !empty($param['match_time_end'])){
            $query->where('match_time','<',strtotime($param['match_time_end']));
        }

        if(isset($param['match_time']) && !empty($param['match_time'])){
            $match_time_arr = explode('~',trim($param['match_time']));
            $query->where('match_time','>=',strtotime(trim($match_time_arr[0])));
            $query->where('match_time','<',strtotime(trim($match_time_arr[1])));
        }

        if(isset($param['hour_s']) && is_numeric($param['hour_s'])){
            $query->where('hour','>=',sprintf("%02d", trim($param['hour_s'])));
        }
        if(isset($param['hour_e']) && is_numeric($param['hour_e'])){
            $query->where('hour','<=',sprintf("%02d", trim($param['hour_e'])));
        }
        if(isset($param['minute_s']) && is_numeric($param['minute_s'])){
            $query->where('minute','>=',sprintf("%02d", trim($param['minute_s'])));
        }
        if(isset($param['minute_e']) && is_numeric($param['minute_e'])){
            $query->where('minute','<=',sprintf("%02d", trim($param['minute_e'])));
        }




        if(isset($param['team']) && !empty($param['team'])){
            $team = trim($param['team']);
            $query->where(function ($query) use ($team){
                $query->where('main_team','like','%'.$team.'%')
                    ->whereOr('visiting_team','like','%'.$team.'%');
            });
        }

        if(isset($param['team_id']) && !empty($param['team_id'])){
            $team_id = explode(',',trim($param['team_id']));
            $query->where(function ($query) use ($team_id){
                $query->where('main_team_id','in',$team_id)
                    ->whereOr('visiting_team_id','in',$team_id);
            });
        }

        return $query;

    }

    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($param = []){
        $query = self::query($param);

        $order = ['match_time' , 'desc'];
        $order = isset($param['field']) && isset($param['order']) ? [trim($param['field']) , trim($param['order'])] : $order;

        $page = intval($param['page'] ?? 1);
        $per_page = intval($param['per_page'] ?? 1);
        $per_page = $per_page < 1 ? 10: $per_page;
        $is_get_all = $param['is_get_all'] ?? 0; //获取所有

        $total = $query->count();
//        Log::error($query->getLastSql());
        if($is_get_all) $per_page = $total;

        $query = self::query($param);
        $query = $query->order($order[0] ?? 'id' , $order[1] ?? 'desc' );
        $list = $query->page($page,$per_page)->select();
//        Log::error($query->getLastSql());
        $list = $list ? collection($list)->toArray() : [];
        $list = self::formatList($list);

        $list_formate = $param['list_formate'] ?? 1;
        $list = self::formateJson($list,$list_formate);

        return Functions::formatList($list,$page,$per_page,$total,$list_formate == 1 ? true : false);
    }

    /**
     * 获取详情
     * @param $id
     * @param array $param
     * sn 单据号
     * @return bool
     */
    public function getDetail($id){
        $id = intval($id);
        if( $id <= 0 ) throw new Exception('参数错误',config('error_code.error'));
        $operator_id = intval(session('admin_id') ?? 0);
//        if( empty($operator_id) ) throw new Exception('操作人不能为空',config('error_code.error'));

        $obj = SportScoreModel::get($id);
        $data = $obj ? $obj->toArray() : null;
        return self::formatInfo($data,$operator_id);

    }

    /**
     * 添加对象
     * @param array $param
     */
    public static function ssAdd($param = []){

        $country_id =  intval($param['country_id']);
        $club_id =  intval($param['club_id']);
        $main_team =  trim($param['main_team']);
        $visiting_team =  trim($param['visiting_team']);
        $match_time =  trim($param['match_time']);
        $ori_match_time =  trim($param['ori_match_time']);

        if(empty($match_time)) throw new \Exception('比赛不能为空',config('error_code.error'));
        if(empty($country_id)) throw new \Exception('所属地区不能为空',config('error_code.error'));
        if(empty($club_id)) throw new \Exception('所属俱乐部不能为空',config('error_code.error'));
        if(empty($main_team)) throw new \Exception('主队不能为空',config('error_code.error'));
        if(empty($visiting_team)) throw new \Exception('客队不能为空',config('error_code.error'));


        $match_time = strtotime($match_time);
        $isExist = SportScoreModel::where('match_time','=',$match_time)
            ->where('main_team','=',$main_team)
            ->where('visiting_team','=',$visiting_team)
            ->count();


        if( $isExist>0 )  SportScoreModel::where('match_time','=',$match_time)
            ->where('main_team','=',$main_team)
            ->where('visiting_team','=',$visiting_team)
            ->delete(true);


        $model = new SportScoreModel();
        $model->ori_match_time = $ori_match_time;
        $model->match_time = $match_time;

        $model->match_month = Functions::formatDateTime($model->match_time,'Y-m-01');
        $model->match_date = Functions::formatDateTime($model->match_time,'Y-m-d');

        $model->hour = Functions::formatDateTime($model->match_time,'H');
        $model->minute = Functions::formatDateTime($model->match_time,'i');

        $model->first_half_m_score = $param['first_half_m_score'] ?? 0;
        $model->first_half_v_score = $param['first_half_v_score'] ?? 0;

        $model->second_half_m_score = $param['second_half_m_score'] ?? 0;
        $model->second_half_v_score = $param['second_half_v_score'] ?? 0;

        $model->full_m_score = $model->first_half_m_score +  $model->second_half_m_score;
        $model->full_v_score = $model->first_half_v_score +  $model->second_half_v_score;


        $model->main_team_id = intval($param['main_team_id']);
        $model->visiting_team_id = intval($param['visiting_team_id']);

        $model->main_team = $main_team;
        $model->visiting_team = $visiting_team;

        $model->club_id = $club_id;
        $model->club_name = $param['club_name'] ?? '';

        $model->country_id = $country_id;
        $model->country_name = $param['country_name'] ?? '';

        $model->remark = $param['remark'] ?? '';
        $model->version = $param['version'] ?? '2020';

        $model->update_user = trim(session('admin_user') ?? '');//录单人
        $model->create_user = $model->update_user ;//录单人

        $model->save();
        $id = $model->id;
        if( $id<=0 ) throw new \Exception('添加失败',config('error_code.error'));


        return [
            'id' => $id,
        ];

    }

    /**
     * 编辑对象
     * @param array $param
     * @param $id
     */
    public static function ssEdit($param = []){


        $id = intval($param['id']);
        $obj = SportScoreModel::get($id);
        if(empty($obj)) throw new \Exception('比分记录不存在',config('error_code.error'));

        if( isset($param['match_time']) ){
            $match_time =  trim($param['match_time']);
            if( empty($match_time) ) throw new \Exception('比赛时间不能为空',config('error_code.error'));
            $match_time = strtotime($match_time);
            $obj->match_time = $match_time;
        }

        if( isset($param['country_id']) ){
            $country_id =  intval($param['country_id']);
            $obj->country_id = $country_id;
            $obj->country_name = Country::get($country_id)->name;        }

        if( isset($param['club_id']) ){
            $club_id =  intval($param['club_id']);
            $obj->club_id = $club_id;
            $obj->club_name = SportClubModel::get($club_id)->name;
        }

        if( isset($param['main_team_id']) && !empty($param['main_team_id']) ) $obj->main_team = $param['main_team_id'];
        if( isset($param['main_team']) && !empty($param['main_team']) ) $obj->main_team = $param['main_team'];

        if( isset($param['visiting_team_id']) && !empty($param['visiting_team_id']) ) $obj->visiting_team_id = $param['visiting_team_id'];
        if( isset($param['visiting_team']) && !empty($param['visiting_team']) ) $obj->visiting_team = $param['visiting_team'];

        if( isset($param['first_half_m_score']) && !empty($param['first_half_m_score']) ) $obj->first_half_m_score = $param['first_half_m_score'];
        if( isset($param['first_half_v_score']) && !empty($param['first_half_v_score']) ) $obj->first_half_v_score = $param['first_half_v_score'];

        if( isset($param['second_half_m_score']) && !empty($param['second_half_m_score']) ) $obj->second_half_m_score = $param['second_half_m_score'];
        if( isset($param['second_half_v_score']) && !empty($param['second_half_v_score']) ) $obj->second_half_v_score = $param['second_half_v_score'];

        $obj->full_m_score = $obj->first_half_m_score + $obj->second_half_m_score;
        $obj->full_v_score = $obj->first_half_v_score + $obj->second_half_v_score;

        $obj->update_user = trim(session('admin_user') ?? '');//录单人

        $obj->save();



        return [
            'id' => $id,
        ];
    }

    /**
     * 删除记录
     * @param $id
     * @return bool
     */
    public static function delete($param){
//        throw new \Exception('暂时不开放删除',config('error_code.error'));

        $id = $param['id'] ?? '';
        if ( empty($id) ) throw new \Exception('参数错误',config('error_code.error'));

        $obj = SportScoreModel::get($id);

        $isExist = SportScoreModel::where('match_time','=',$obj->match_time)
            ->where('main_team','=',$obj->main_team)
            ->where('visiting_team','=',$obj->visiting_team)->count() > 1 ? true : false;

//        if( !$isExist ) throw new \Exception('无重复数据暂时不开放删除',config('error_code.error'));

        if( is_numeric($id) ){
            SportScoreModel::destroy(['id'=>$id]);
        }else{
            $ids = explode(',',trim($id));
            foreach ($ids as $id){
                SportScoreModel::destroy(['id'=>$id]);
            }
        }
        return  true;
    }

    /**
     * 格式化
     * @param $value
     * @return mixed
     */
    public static function format($value){
        if(isset($value['match_time'])) $value['match_time'] = Functions::formatDateTime($value['match_time'],'Y-m-d H:i');
        if(isset($value['create_time'])) $value['create_time'] = Functions::formatDateTime($value['create_time']);
        if(isset($value['update_time'])) $value['update_time'] = Functions::formatDateTime($value['update_time']);

        //上半场比分
        $value['first_half_score'] = $value['first_half_m_score'] . ' - ' . $value['first_half_v_score'];
        $value['first_half_dx'] = ($value['first_half_m_score'] + $value['first_half_v_score']) ;
        //下半场比分
        $value['second_half_score'] = $value['second_half_m_score'] . ' - ' . $value['second_half_v_score'];
        $value['second_half_dx'] = ($value['second_half_m_score'] +  $value['second_half_v_score']);
        //全场场比分
        $value['full_score'] = $value['full_m_score'] . ' - ' . $value['full_v_score'];
        $value['full_dx'] = ($value['full_m_score'] + $value['full_v_score']);

        return $value;
    }

    /**
     * 格式化 info
     * @param $info
     */
    public static function formatInfo($info){
        if(!empty($info)){
            $info = self::format($info);
        }
        return $info;
    }

    /**
     * 格式化 list
     * @param $list
     * @param bool $isGetAssetsSn 是否获取 支出的资产编号 默认否
     * @return mixed
     */
    public static function formatList($list){

        if(!empty($list)){

            $clubList = SportClub::getList([
                'is_get_all' => 1,
                'order' => 'id asc',
            ])['list'];
            $clubList = Functions::getKeyValueList($clubList,'id');
            foreach ($list as $key => &$value){
                $value['club_name'] = $clubList[$value['club_id']]['name'] ?? '';
                $value = self::format($value);
            }
        }
        return $list;
    }

    protected static function formateJson($list,$formate_type = 1){
        if($formate_type == 1) return $list;
        if($formate_type == 2){//
            $data = [];
            foreach ($list as $key => $value){
                $value['team'] = $value['main_team'] .' ~ '. $value['visiting_team'];
                $value['score'] = '( '.$value['first_half_score'] .' )( '. $value['second_half_score'].' ) ( '. $value['full_score'].' )';
                $value['da_xi'] = '( '.$value['first_half_dx'] .' )( '. $value['second_half_dx'].' ) ( '. $value['full_dx'].' )';
                $date = Functions::formatDate(strtotime($value['match_time']));
                $data[$date][$value['country_id']][] = $value;
            }
            return $data;
        }

        return $list;
    }

    /**
     * 抓取数据
     * @param string $content
     */
    public static function graspScores($lines = '',$version = 2020){

        $total = $success = 0;
        if(!empty($lines)){

            $scores = [];
            /// 独家FIFA20
            $team = $main_team = $visiting_team = '';

            $clubList = collection(SportClubModel::with(['country'])->where('version','=',$version)->select())->toArray();
            $clubList = Functions::getKeyValueList($clubList,'id');

            $teamList = SportTeamModel::all(function ($query) use ($clubList){
                $query->where('club_id','in',array_keys($clubList));
            });
            $teamList = Functions::getKeyValueList($teamList,'full_name');

//            Log::write( $clubList );
//            Log::write( $teamList );
            $year = 2020;
            $clubName = '';

            foreach ($lines as $key => $line){

                if(stripos($line,'独家FIFA') !== false ){

                    $line = trim($line);
                    $line = trim(str_replace('VS - IM','',$line));
                    $line = trim(str_replace('独家FIFA','',$line));

                    $year = substr($line,0,2);
                    $clubName = 'VS - IM 独家FIFA'. $year .' ' . substr($line,2);

                    $year = '20' . $year;
                    continue;
                }else if(stripos($line,'独家PES') !== false ){
                    $clubName = '';
                }

                if( $year != $version ) continue;
                if(empty($clubName)) continue;
//                throw new Exception(__($clubName.'俱乐部不存在'));

                if(stripos($line,'VS - ') !== false ){
                    $team = trim($line);

                    if( strpos($team,'vs') > 0 ){
                        $team = str_replace('vs','',$team);
                        $team = trim($team);
                        $main_team = $team;//主队

                        if(!isset($teamList[$main_team])){
                            // 不存在则添加球队
                            $clubObj = Club::get(['name' => $clubName]);
                            if( empty($clubObj) ) throw new Exception(__($clubName.' 俱乐部不存在'));

                            $teamList[$team] = SportTeam::add([
                                'name' => $team,
                                'full_name' => $team,
                                'club_id' => $clubObj->id,
                            ]);
                        }
                    }else{
                        $visiting_team = $team;// 客队
                        if(!isset($teamList[$visiting_team])){
                            // 不存在则添加球队
                            $clubObj = Club::get(['name' => $clubName]);
                            if( empty($clubObj) ) throw new Exception(__($clubName.' 俱乐部不存在'));

                            $teamList[$team] = SportTeam::add([
                                'name' => $team,
                                'full_name' => $team,
                                'club_id' => $clubObj->id,
                            ]);
                        }
                        
                        $ori_match_time = trim($lines[$key-3]) . ' ' . trim($lines[$key-2]);
                        $match_time = self::formatMatchTime(trim($lines[$key-3]),trim($lines[$key-2]));

                        $fisrt_half_str = trim($lines[$key+1]);
                        $second_half_str = trim($lines[$key+2]);
                        $full_score_str = trim($lines[$key+3]);

                        $fisrt_half = explode('-',$fisrt_half_str);
                        $second_half = explode('-',$second_half_str);
                        $full_score = explode('-',$full_score_str);

//                    Log::write('-------*********************-------' );
//                    Log::write( $visiting_team );
//                    Log::write( $teamList[$main_team] );
//                    continue;

                        $club_id = $teamList[$main_team]['club_id'];

                        $score = [
                            'ori_match_time' => $ori_match_time,
                            'match_time' => $match_time,

                            'version' => $version,
                            'club_id' => $club_id,
                            'club_name' => $clubList[$club_id]['name'],
                            'country_id' => $clubList[$club_id]['country_id'],
                            'country_name' => $clubList[$club_id]['country']['name'],

                            'main_team_id' => $teamList[$main_team]['id'],
                            'visiting_team_id' => $teamList[$visiting_team]['id'],

                            'main_team' => $main_team,
                            'visiting_team' => $visiting_team,

                            'first_half_m_score' => intval($fisrt_half[0] ?? '*'),
                            'first_half_v_score' => intval($fisrt_half[1] ?? '*'),

                            'second_half_m_score' => intval($second_half[0] ?? '*'),
                            'second_half_v_score' => intval($second_half[1] ?? '*'),

                            'full_m_score' => intval($full_score[0] ?? '*'),
                            'full_v_score' => intval($full_score[1] ?? '*'),

                            'remark' => '',

                        ];

                        if( !isset($fisrt_half[0]) || !isset($fisrt_half[1]) || !isset($second_half[0]) || !isset($second_half[1]) || !isset($full_score[0]) || !isset($full_score[1]) ) {
                            Log::write($fisrt_half_str);
                            Log::write($second_half_str);
                            Log::write($full_score_str);

                            Log::write($score);

                            $score['remark'] = '比分错误：('. $fisrt_half_str .')' . '('.$second_half_str.')'.'('.$full_score_str.')';
                        }
                        $scores[] = $score;


                    }
                }
            }


            if(empty($match_time)) $match_time = date('Y-m-d');
            $match_time = date('Y-m-d',strtotime($match_time));
           
            // 删除当天比分
            SportScoreModel::destroy(function ($query) use ($match_time,$version){
                $query->where('match_date','=',$match_time)->where('version','=',$version);
            },true);


            /*$total = count($scores);
            if($scores){
                $resultObj = (new SportScoreModel)->saveAll($scores);
                $success = collection($resultObj)->count();
            }*/

            if( count($scores) >= 100 ) sleep(5);// 延时5秒

            foreach ($scores as $score){
                $total++;
                try{
                    self::ssAdd($score);
                    $success++;
                }catch (\Exception $e){
                    Log::write('----------- 添加失败数据start ----------');
                    Log::write($score);
                    Log::write($e->getMessage());
                }
            }

        }

        return [
            'total'=>$total,
            'success'=>$success,
        ];
    }

    private static function formatMatchTime($date,$time){
        $date = trim($date);
        $date = str_replace('\\','/',$date);
        $dateArr = explode('/',$date);
        $date = $dateArr[2]. '-' .$dateArr[1] . '-' . $dateArr[0];

        $time = strtolower(trim($time));
        if(stripos($time,'am') !== false){
            $time = str_replace('am','',$time);
            $addHour = 0;
        }else{
            $time = str_replace('pm','',$time);
            $addHour = 12;
        }

        return Functions::formatDateTime(strtotime($date . ' ' .$time));

        $timeArr = explode(':',$time);
        if( $timeArr[0] == 12 ) $timeArr[0] = '00';

        $match_time_str = $date . ' ' . trim($timeArr[0]) . ':' . trim($timeArr[1]) .':00';
        return Functions::formatDateTime(strtotime($match_time_str) +  $addHour * 60 * 60);
    }

    private static function formatMatchTimeFromJson($match_time){
        $match_time = trim($match_time);
        $match_time = str_replace('T',' ',$match_time).'R';
        $match_time = str_replace('-04:00R','',$match_time);
        $addHour = 12;
        return Functions::formatDateTime(strtotime($match_time) +  $addHour * 60 * 60);
    }


    /**
     * 统计分析
     * @param $mStart
     * @param $mEnd
     * @return array
     */
    public static function statAnalyseTM($param = []){
        $list = self::query($param)->field('*,(first_half_m_score + first_half_v_score) as first_score,(second_half_m_score + second_half_v_score) as second_score,(full_m_score + full_v_score) as full_score')->order('id','desc')->select()->toArray();

        $data = [];
        $chart = [];

        if( $list ){
            $first_z  = $first_o = $first_t = $first_to = $first_thr = 0;//上半场
            $second_z  = $second_o = $second_t = $second_to = $second_thr = 0;//下半场
            $full_z  = $full_o = $full_t = $full_to = $full_thr = 0;//全场
            foreach($list as $value){
                $first_z = ($value['first_score'] == 0 ? 1 : 0);
                $first_o = ($value['first_score'] == 1 ? 1 : 0);
                $first_t = ($value['first_score'] == 2 ? 1 : 0);
                $first_to = ($value['first_score'] >= 2 ? 1 : 0);
                $first_thr = ($value['first_score'] >= 3 ? 1 : 0);


                $second_z = ($value['second_score'] == 0 ? 1 : 0);
                $second_o = ($value['second_score'] == 1 ? 1 : 0);
                $second_t = ($value['second_score'] == 2 ? 1 : 0);
                $second_to = ($value['second_score'] >= 2 ? 1 : 0);
                $second_thr = ($value['second_score'] >= 3 ? 1 : 0);

                $full_z = ($value['full_score'] == 0 ? 1 : 0);
                $full_o = ($value['full_score'] == 1 ? 1 : 0);
                $full_t = ($value['full_score'] == 2 ? 1 : 0);
                $full_to = ($value['full_score'] >= 2 ? 1 : 0);
                $full_thr = ($value['full_score'] >= 3 ? 1 : 0);


                $data[$value['match_date']][$value['country_id']]['first_zero'] = ($data[$value['match_date']][$value['country_id']]['first_zero'] ?? 0) + $first_z;
                $data[$value['match_date']][$value['country_id']]['first_one'] = ($data[$value['match_date']][$value['country_id']]['first_one'] ?? 0) + $first_o;
                $data[$value['match_date']][$value['country_id']]['first_two'] = ($data[$value['match_date']][$value['country_id']]['first_two'] ?? 0) + $first_t;
                $data[$value['match_date']][$value['country_id']]['first_o_two'] = ($data[$value['match_date']][$value['country_id']]['first_o_two'] ?? 0) + $first_to;
                $data[$value['match_date']][$value['country_id']]['first_thr'] = ($data[$value['match_date']][$value['country_id']]['first_thr'] ?? 0) + $first_thr;

                $data[$value['match_date']][$value['country_id']]['second_zero'] = ($data[$value['match_date']][$value['country_id']]['second_zero'] ?? 0) + $second_z;
                $data[$value['match_date']][$value['country_id']]['second_one'] = ($data[$value['match_date']][$value['country_id']]['second_one'] ?? 0) + $second_o;
                $data[$value['match_date']][$value['country_id']]['second_two'] = ($data[$value['match_date']][$value['country_id']]['second_two'] ?? 0) + $second_t;
                $data[$value['match_date']][$value['country_id']]['second_o_two'] = ($data[$value['match_date']][$value['country_id']]['second_o_two'] ?? 0) + $second_to;
                $data[$value['match_date']][$value['country_id']]['second_thr'] = ($data[$value['match_date']][$value['country_id']]['second_thr'] ?? 0) + $second_thr;

                $data[$value['match_date']][$value['country_id']]['full_zero'] = ($data[$value['match_date']][$value['country_id']]['full_zero'] ?? 0) + $full_z;
                $data[$value['match_date']][$value['country_id']]['full_one'] = ($data[$value['match_date']][$value['country_id']]['full_one'] ?? 0) + $full_o;
                $data[$value['match_date']][$value['country_id']]['full_two'] = ($data[$value['match_date']][$value['country_id']]['full_two'] ?? 0) + $full_t;
                $data[$value['match_date']][$value['country_id']]['full_o_two'] = ($data[$value['match_date']][$value['country_id']]['full_o_two'] ?? 0) + $full_to;
                $data[$value['match_date']][$value['country_id']]['full_thr'] = ($data[$value['match_date']][$value['country_id']]['full_thr'] ?? 0) + $full_thr;

                $data[$value['match_date']][$value['country_id']]['m_total'] = ($data[$value['match_date']][$value['country_id']]['m_total'] ?? 0 ) + 1;
            }

            // 占比
            foreach ($data as $key => $value){
                foreach ($value as $c_id => $val ){
                    $data[$key][$c_id]['first_zero_per'] = Functions::formatPrice($val['first_zero'] / $val['m_total']);
                    $data[$key][$c_id]['first_one_per'] = Functions::formatPrice($val['first_one'] / $val['m_total']);
                    $data[$key][$c_id]['first_two_per'] = Functions::formatPrice($val['first_two'] / $val['m_total']);
                    $data[$key][$c_id]['first_o_two_per'] = Functions::formatPrice($val['first_o_two'] / $val['m_total']);
                    $data[$key][$c_id]['first_thr_per'] = Functions::formatPrice($val['first_thr'] / $val['m_total']);

                    $data[$key][$c_id]['second_zero_per'] = Functions::formatPrice($val['second_zero'] / $val['m_total']);
                    $data[$key][$c_id]['second_one_per'] = Functions::formatPrice($val['second_one'] / $val['m_total']);
                    $data[$key][$c_id]['second_two_per'] = Functions::formatPrice($val['second_two'] / $val['m_total']);
                    $data[$key][$c_id]['second_o_two_per'] = Functions::formatPrice($val['second_o_two'] / $val['m_total']);
                    $data[$key][$c_id]['second_thr_per'] = Functions::formatPrice($val['second_thr'] / $val['m_total']);

                    $data[$key][$c_id]['full_zero_per'] = Functions::formatPrice($val['full_zero'] / $val['m_total']);
                    $data[$key][$c_id]['full_one_per'] = Functions::formatPrice($val['full_one'] / $val['m_total']);
                    $data[$key][$c_id]['full_two_per'] = Functions::formatPrice($val['full_two'] / $val['m_total']);
                    $data[$key][$c_id]['full_o_two_per'] = Functions::formatPrice($val['full_o_two'] / $val['m_total']);
                    $data[$key][$c_id]['full_thr_per'] = Functions::formatPrice($val['full_thr'] / $val['m_total']);
                }
            }

            $labels = [];
            foreach ($data as $key => $value){
                array_push($labels,$key);
                foreach ($value as $c_id => $val ){
                    $chart[$c_id]['labels'] = $labels;

                    $chart[$c_id]['m_total'] = $val['m_total'];

                    $chart[$c_id]['first_zero'][] = $val['first_zero'];
                    $chart[$c_id]['first_one'][] = $val['first_one'];
                    $chart[$c_id]['first_two'][] = $val['first_two'];
                    $chart[$c_id]['first_o_two'][] = $val['first_o_two'];
                    $chart[$c_id]['first_thr'][] = $val['first_thr'];

                    $chart[$c_id]['second_zero'][] = $val['second_zero'];
                    $chart[$c_id]['second_one'][] = $val['second_one'];
                    $chart[$c_id]['second_two'][] = $val['second_two'];
                    $chart[$c_id]['second_o_two'][] = $val['second_o_two'];
                    $chart[$c_id]['second_thr'][] = $val['second_thr'];

                    $chart[$c_id]['full_zero'][] = $val['full_zero'];
                    $chart[$c_id]['full_one'][] = $val['full_one'];
                    $chart[$c_id]['full_two'][] = $val['full_two'];
                    $chart[$c_id]['full_o_two'][] = $val['full_o_two'];
                    $chart[$c_id]['full_thr'][] = $val['full_thr'];


                    // 占比
                    $chart[$c_id]['first_zero_per'][] = $val['first_zero_per'];
                    $chart[$c_id]['first_one_per'][] = $val['first_one_per'];
                    $chart[$c_id]['first_two_per'][] = $val['first_two_per'];
                    $chart[$c_id]['first_o_two_per'][] = $val['first_o_two_per'];
                    $chart[$c_id]['first_thr_per'][] = $val['first_thr_per'];

                    $chart[$c_id]['second_zero_per'][] = $val['second_zero_per'];
                    $chart[$c_id]['second_one_per'][] = $val['second_one_per'];
                    $chart[$c_id]['second_two_per'][] = $val['second_two_per'];
                    $chart[$c_id]['second_o_two_per'][] = $val['second_o_two_per'];
                    $chart[$c_id]['second_thr_per'][] = $val['second_thr_per'];

                    $chart[$c_id]['full_zero_per'][] = $val['full_zero_per'];
                    $chart[$c_id]['full_one_per'][] = $val['full_one_per'];
                    $chart[$c_id]['full_two_per'][] = $val['full_two_per'];
                    $chart[$c_id]['full_o_two_per'][] = $val['full_o_two_per'];
                    $chart[$c_id]['full_thr_per'][] = $val['full_thr_per'];

                }
            }

            foreach ($chart as $key => $value){

                krsort($chart[$key]['labels']);

                krsort($chart[$key]['first_zero']);
                krsort($chart[$key]['first_one']);
                krsort($chart[$key]['first_two']);
                krsort($chart[$key]['first_o_two']);
                krsort($chart[$key]['first_thr']);

                krsort($chart[$key]['second_zero']);
                krsort($chart[$key]['second_one']);
                krsort($chart[$key]['second_two']);
                krsort($chart[$key]['second_o_two']);
                krsort($chart[$key]['second_thr']);

                krsort($chart[$key]['full_zero']);
                krsort($chart[$key]['full_one']);
                krsort($chart[$key]['full_two']);
                krsort($chart[$key]['full_o_two']);
                krsort($chart[$key]['full_thr']);

                $chart[$key]['labels'] = array_values($chart[$key]['labels']);

                $chart[$key]['first_zero'] = array_values($chart[$key]['first_zero']);
                $chart[$key]['first_one'] = array_values($chart[$key]['first_one']);
                $chart[$key]['first_two'] = array_values($chart[$key]['first_two']);
                $chart[$key]['first_o_two'] = array_values($chart[$key]['first_o_two']);
                $chart[$key]['first_thr'] = array_values($chart[$key]['first_thr']);

                $chart[$key]['second_zero'] = array_values($chart[$key]['second_zero']);
                $chart[$key]['second_one'] = array_values($chart[$key]['second_one']);
                $chart[$key]['second_two'] = array_values($chart[$key]['second_two']);
                $chart[$key]['second_o_two'] = array_values($chart[$key]['second_o_two']);
                $chart[$key]['second_thr'] = array_values($chart[$key]['second_thr']);

                $chart[$key]['full_zero'] = array_values($chart[$key]['full_zero']);
                $chart[$key]['full_one'] = array_values($chart[$key]['full_one']);
                $chart[$key]['full_two'] = array_values($chart[$key]['full_two']);
                $chart[$key]['full_o_two'] = array_values($chart[$key]['full_o_two']);
                $chart[$key]['full_thr'] = array_values($chart[$key]['full_thr']);


                //占比
                krsort($chart[$key]['first_zero_per']);
                krsort($chart[$key]['first_one_per']);
                krsort($chart[$key]['first_two_per']);
                krsort($chart[$key]['first_o_two_per']);
                krsort($chart[$key]['first_thr_per']);

                krsort($chart[$key]['second_zero_per']);
                krsort($chart[$key]['second_one_per']);
                krsort($chart[$key]['second_two_per']);
                krsort($chart[$key]['second_o_two_per']);
                krsort($chart[$key]['second_thr_per']);

                krsort($chart[$key]['full_zero_per']);
                krsort($chart[$key]['full_one_per']);
                krsort($chart[$key]['full_two_per']);
                krsort($chart[$key]['full_o_two_per']);
                krsort($chart[$key]['full_thr_per']);

                $chart[$key]['first_zero_per'] = array_values($chart[$key]['first_zero_per']);
                $chart[$key]['first_one_per'] = array_values($chart[$key]['first_one_per']);
                $chart[$key]['first_two_per'] = array_values($chart[$key]['first_two_per']);
                $chart[$key]['first_o_two_per'] = array_values($chart[$key]['first_o_two_per']);
                $chart[$key]['first_thr_per'] = array_values($chart[$key]['first_thr_per']);

                $chart[$key]['second_zero_per'] = array_values($chart[$key]['second_zero_per']);
                $chart[$key]['second_one_per'] = array_values($chart[$key]['second_one_per']);
                $chart[$key]['second_two_per'] = array_values($chart[$key]['second_two_per']);
                $chart[$key]['second_o_two_per'] = array_values($chart[$key]['second_o_two_per']);
                $chart[$key]['second_thr_per'] = array_values($chart[$key]['second_thr_per']);

                $chart[$key]['full_zero_per'] = array_values($chart[$key]['full_zero_per']);
                $chart[$key]['full_one_per'] = array_values($chart[$key]['full_one_per']);
                $chart[$key]['full_two_per'] = array_values($chart[$key]['full_two_per']);
                $chart[$key]['full_o_two_per'] = array_values($chart[$key]['full_o_two_per']);
                $chart[$key]['full_thr_per'] = array_values($chart[$key]['full_thr_per']);

            }
        }

        return [ 'table' => $data,'chart' => $chart];
    }

    /**
     * 下载比分
     * @param array $param
     */
    public static function snycLoadScore($param = []){
        $url = config('url.score');

        $start = strtotime(date('Y-m-d 00:00:00',time()));
        $end = strtotime(date('Y-m-d 23:59:59',time()));

        if(isset($param['match_time']) && !empty($param['match_time'])){
            $match_time_arr = explode('~',trim($param['match_time']));
            $start = strtotime(trim($match_time_arr[0]));
            $end = strtotime(trim($match_time_arr[1]));
        }

        $start -= 12*60*60;
        $end -= 12*60*60;

        $start = Functions::formatDateTime($start);
        $end = Functions::formatDateTime($end);

//        $url = trim($url,'/').'/'.$start.'/'.$end;

        $param = [
            'SportId' => 1,
            'StartDate' => $start,
            'EndDate' => $end,
        ];

//        Log::write($url);
        $json = Https::post($url,$param);
//        Log::write($json);
        $array = json_decode($json, true);

//        Log::write('获取时间：'.Functions::formatDateTime(time()));
//        Log::write($array);

        $scores = [];
        $total = $success = 0;
        $list = $array['lrr'] ?? [];

        $clubList = SportClubModel::all([]);
        $clubList = Functions::getKeyValueList($clubList,'id');

        $teamList = SportTeamModel::all([]);
        $teamList = Functions::getKeyValueList($teamList,'full_name');

        foreach ($list as $key => $mList){

            if(stripos($mList['ln2'],'独家FIFA') === false && stripos($mList['ln2'],'独家PES') === false ) continue;

            if(stripos($mList['ln2'],'VS - ') !== false ){

                foreach ($mList['mrl'] as $pValue) {

                    $main_team = $pValue['ht'];//主队
                    $visiting_team = $pValue['at'];// 客队

                    $main_team = 'VS - '.trim(str_replace('VS -','',$main_team));
                    $visiting_team = 'VS - '.trim(str_replace('VS -','',$visiting_team));

                    if( !isset($teamList[$main_team]) || !isset($teamList[$visiting_team]) ) continue;
                    $ori_match_time = $pValue['mdt'];
                    $match_time = self::formatMatchTimeFromJson($ori_match_time);

                    $prList = $pValue['prl'];


                    $fisrt_half_str =  ($prList[1]['c']) ?  '取消' : $prList[1]['hs'].'-'.$prList[1]['as'];
                    $second_half_str = ($prList[2]['c']) ?  '取消' :  $prList[2]['hs'].'-'.$prList[2]['as'];
                    $full_score_str =  ($prList[0]['c']) ?  '取消' : $prList[0]['hs'].'-'.$prList[0]['as'];

                    $fisrt_half = explode('-',$fisrt_half_str);
                    $second_half = explode('-',$second_half_str);
                    $full_score = explode('-',$full_score_str);


                    $club_id = $teamList[$main_team]['club_id'];

                    $score = [
                        'ori_match_time' => $ori_match_time,
                        'match_time' => $match_time,

                        'club_id' => $club_id,
                        'club_name' => $clubList[$club_id]['name'],
                        'country_id' => $clubList[$club_id]['country_id'],
                        'country_name' => $clubList[$club_id]['country_name'],

                        'main_team_id' => $teamList[$main_team]['id'],
                        'visiting_team_id' => $teamList[$visiting_team]['id'],

                        'main_team' => $main_team,
                        'visiting_team' => $visiting_team,

                        'first_half_m_score' => intval($fisrt_half[0] ?? '*'),
                        'first_half_v_score' => intval($fisrt_half[1] ?? '*'),

                        'second_half_m_score' => intval($second_half[0] ?? '*'),
                        'second_half_v_score' => intval($second_half[1] ?? '*'),

                        'full_m_score' => intval($full_score[0] ?? '*'),
                        'full_v_score' => intval($full_score[1] ?? '*'),

                        'remark' => '',

                    ];

                    if( !isset($fisrt_half[0]) || !isset($fisrt_half[1]) || !isset($second_half[0]) || !isset($second_half[1]) || !isset($full_score[0]) || !isset($full_score[1]) ) {
                        Log::write($fisrt_half_str);
                        Log::write($second_half_str);
                        Log::write($full_score_str);

                        Log::write($score);

                        $score['remark'] = '比分错误：('. $fisrt_half_str .')' . '('.$second_half_str.')'.'('.$full_score_str.')';
                    }
                    $scores[] = $score;

                }
            }
        }


        if(!empty( $scores )){
            foreach ($scores as $score){
                $total++;
                try{
                    self::ssAdd($score);
                    $success++;
                }catch (\Exception $e){
                    Log::write('----------- 添加失败数据start ----------');
                    Log::write($score);
                    Log::write($e->getMessage());
                }
            }
        }

//        Log::write('更新时间：'.Functions::formatDateTime(time()));
//        Log::write($scores);

        return [
            'total'=>$total,
            'success'=>$success,
        ];

    }
}